

package com.asisto.controller
import com.asisto.model.Tarea
import com.asisto.model.Empleado
import java.text.SimpleDateFormat
import grails.converters.*

class EventoJson {

    Integer id
    String start
    String end
    String title
    String clase
}


class TareaController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def calendarioSemanal = {}

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ tareaInstanceList: Tarea.list( params ), tareaInstanceTotal: Tarea.count() ]
    }

    def show = {
        def tareaInstance = Tarea.get( params.id )

        if(!tareaInstance) {
            flash.message = "Tarea not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ tareaInstance : tareaInstance ] }
    }

    def delete = {
        def tareaInstance = Tarea.get( params.id )
        if(tareaInstance) {
            try {
                tareaInstance.delete(flush:true)
                flash.message = "Tarea ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Tarea ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Tarea not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def tareaInstance = Tarea.get( params.id )

        if(!tareaInstance) {
            flash.message = "Tarea not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ tareaInstance : tareaInstance ]
        }
    }

    def update = {
        def tareaInstance = Tarea.get( params.id )
        if(tareaInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(tareaInstance.version > version) {
                    
                    tareaInstance.errors.rejectValue("version", "tarea.optimistic.locking.failure", "Another user has updated this Tarea while you were editing.")
                    render(view:'edit',model:[tareaInstance:tareaInstance])
                    return
                }
            }
            tareaInstance.properties = params
            if(!tareaInstance.hasErrors() && tareaInstance.save()) {
                flash.message = "Tarea ${params.id} updated"
                redirect(action:show,id:tareaInstance.id)
            }
            else {
                render(view:'edit',model:[tareaInstance:tareaInstance])
            }
        }
        else {
            flash.message = "Tarea not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def tareaInstance = new Tarea()
        tareaInstance.properties = params
        return ['tareaInstance':tareaInstance]
    }

    def save = {
        def tareaInstance = new Tarea(params)
        def fechaStart
        def fechaEnd

        println "params: $params"

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm")

        def fecha1 = params.fecha1
        def fecha2 = params.fecha2
        def horaInicio = params.horaInicio
        def horaFin = params.horaFin
        def minutosFin = params.minutosFin
        def minutosInicio = params.minutosInicio

        if (fecha1 && horaInicio && minutosInicio) {
            def inicio = "$fecha1 $horaInicio:$minutosInicio"
            println "fecha inicio: $inicio"
            fechaStart = sdf.parse(inicio)
        }

        if (fecha2 && horaFin && minutosFin) {
            def fin = "$fecha2 $horaFin:$minutosFin"
            println "fecha fin: $fin"
            fechaEnd = sdf.parse(fin)
        }


        println "fechaStart: $fechaStart - fechaEnd: $fechaEnd"

        tareaInstance.fechaInicio = fechaStart
        tareaInstance.fechaFin = fechaEnd


        tareaInstance.validate()

        if(!tareaInstance.hasErrors() && tareaInstance.save()) {
            flash.message = "Tarea ${tareaInstance.id} creada"
            redirect(action:show,id:tareaInstance.id)
        }
        else {
            render(view:'create',model:[tareaInstance:tareaInstance])
        }


        /*
        if(!tareaInstance.hasErrors() && tareaInstance.save()) {
            flash.message = "Tarea ${tareaInstance.id} created"
            redirect(action:show,id:tareaInstance.id)
        }
        else {
            render(view:'create',model:[tareaInstance:tareaInstance])
        }*/
    }


    def semanajson = {

        Date fechaStart = null
        Date fechaEnd = null

        println "params = $params"

        def start = params?.start
        def end = params?.end

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd")

        if (start) {
            fechaStart = sdf.parse(start)
        }

        if (end) {
            fechaEnd = sdf.parse(end)
        }

        println "busca eventos entre ${fechaStart} y ${fechaEnd}"

        def eventos = []

        params.max = 10
        eventos = Tarea.list(params)

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+10:00'")

        def listaJson = []
        listaJson = eventos.collect {
            println "evento: ${it.id} - start: ${it.fechaInicio} - end: ${it.fechaFin}"

            def inicio = sdf2.format(it.fechaInicio)
            def fin = sdf2.format(it.fechaFin)
            
            new EventoJson(id: it.id, start:inicio, end:fin, title:it.descripcion, clase:'tarea')
        }

        println "lista objetos json"
        listaJson.each {
            println "evento: ${it.id} - start: ${it.start} - end: ${it.end}"
        }

        render listaJson as JSON
    }

    def creaEvento = {

        Date fechaInicio = null
        Date fechaFin = null

        def title = params.title
        def inicio = params.start
        def fin = params.end
        println "titulo: $title - inicio: $inicio - fin: $fin"


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd-HH:mm")

        try {
            if (inicio) {
                fechaInicio = sdf.parse(inicio)
            }

            if (fin) {
                fechaFin = sdf.parse(fin)
            }

            def tarea = new Tarea()
            tarea.fechaInicio = fechaInicio
            tarea.fechaFin = fechaFin
            tarea.descripcion = title

            //TODO
            def empleado = Empleado.get(1)

            println "empleado $empleado"
            tarea.empleado = empleado

            if(!tarea.hasErrors() && tarea.save()) {
                flash.message = "Tarea ${tarea.id} creada"
                render("Tarea creada")
            }
            else {
                flash.message = "Error creando tarea"
                render("Error creacion tarea")
            }
        } catch (Exception e) {
            println "error - $e"
            flash.message = "Error creando tarea"
            render("Error creacion tarea")
        }


       
    }
}
